package cn.nexttec.noteplayer.ui.reflow

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView.OnScrollListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import cn.nexttec.noteplayer.common.Preference
import cn.nexttec.noteplayer.common.gson
import cn.nexttec.noteplayer.databinding.FragmentNotesBinding
import cn.nexttec.noteplayer.ui.activities.EditorActivity
import cn.nexttec.noteplayer.ui.activities.SearchActivity
import cn.nexttec.noteplayer.ui.adapters.NoteAdapter
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject

@AndroidEntryPoint
class NoteFragment : Fragment() {

    @Inject lateinit var preference: Preference
    private lateinit var viewModel: NoteViewModel
    private var _binding: FragmentNotesBinding? = null
    private lateinit var adapter: NoteAdapter

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {


        _binding = FragmentNotesBinding.inflate(inflater, container, false)
        binding.rvList.layoutManager = LinearLayoutManager(requireContext())
        adapter = NoteAdapter(onItemClicked = {
            val intent = Intent(requireContext(), EditorActivity::class.java)
            intent.putExtra("note", it)
            startActivity(intent)
        }, onItemLongClicked = {

        })

        binding.searchBox.setOnClickListener {
            SearchActivity.startActivity(requireContext(),0)
        }

        binding.llSearch.setOnClickListener {
            SearchActivity.startActivity(requireContext(), 1)
        }
        binding.rvList.adapter = adapter
        viewModel = ViewModelProvider(this).get(NoteViewModel::class.java)

        viewModel.notes.observe(viewLifecycleOwner) {
            adapter.appendNotes(it)
        }
        viewModel.loadNotes()


        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }

    override fun onResume() {
        super.onResume()
        viewModel.loadNotes()
    }
}